package com.soloyogame.anitoys.my.web.controller.front.account;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.qiniu.util.StringMap;
import com.soloyogame.anitoys.db.bean.Letter;
import com.soloyogame.anitoys.db.commond.Account;
import com.soloyogame.anitoys.db.commond.AccountFinance;
import com.soloyogame.anitoys.db.commond.AccountSecurity;
import com.soloyogame.anitoys.db.commond.Address;
import com.soloyogame.anitoys.db.commond.Area;
import com.soloyogame.anitoys.db.commond.CartInfo;
import com.soloyogame.anitoys.db.commond.Email;
import com.soloyogame.anitoys.db.commond.Favorite;
import com.soloyogame.anitoys.db.commond.LoginTypeEnum;
import com.soloyogame.anitoys.db.commond.MyOrderRepairs;
import com.soloyogame.anitoys.db.commond.NotifyTemplate;
import com.soloyogame.anitoys.db.commond.Order;
import com.soloyogame.anitoys.db.commond.OrderRepairs;
import com.soloyogame.anitoys.db.commond.OrderSimpleReport;
import com.soloyogame.anitoys.db.commond.Orderpay;
import com.soloyogame.anitoys.db.commond.Product;
import com.soloyogame.anitoys.db.commond.SystemSetting;
import com.soloyogame.anitoys.db.page.PagerModel;
import com.soloyogame.anitoys.my.web.controller.BaseController;
import com.soloyogame.anitoys.my.web.controller.front.util.LoginUserHolder;
import com.soloyogame.anitoys.my.web.controller.front.util.RequestHolder;
import com.soloyogame.anitoys.my.web.controller.front.util.SMSUtils;
import com.soloyogame.anitoys.service.AccountFinanceService;
import com.soloyogame.anitoys.service.AccountSecurityService;
import com.soloyogame.anitoys.service.AccountService;
import com.soloyogame.anitoys.service.AddressService;
import com.soloyogame.anitoys.service.AreaService;
import com.soloyogame.anitoys.service.EmailService;
import com.soloyogame.anitoys.service.FavoriteService;
import com.soloyogame.anitoys.service.OrderRepairsService;
import com.soloyogame.anitoys.service.OrderService;
import com.soloyogame.anitoys.service.OrderpayService;
import com.soloyogame.anitoys.service.ProductService;
import com.soloyogame.anitoys.service.SystemSettingService;
import com.soloyogame.anitoys.util.AddressUtils;
import com.soloyogame.anitoys.util.DateTimeUtil;
import com.soloyogame.anitoys.util.MD5;
import com.soloyogame.anitoys.util.PropertiesUtil;
import com.soloyogame.anitoys.util.cache.RedisCacheProvider;
import com.soloyogame.anitoys.util.email.EmailUtils;
import com.soloyogame.anitoys.util.email.Mail;
import com.soloyogame.anitoys.util.email.SendCloud;
import com.soloyogame.anitoys.util.front.FrontContainer;
import com.soloyogame.anitoys.util.qiniu.QiniuUploadManager;
import com.soloyogame.anitoys.util.qiniu.TestConfig;


/**
 * 门户会员服务类
 * @author shaojian
 */
@Controller("frontAccountController")
@RequestMapping("account")
public class AccountAction extends BaseController<Account> 
{
	/**
	 * 短信模板变量
	 */
    private static String lettermodel = "亲爱的用户，本次验证码为#code#，请尽快完成验证，5分钟内有效。";       
    static Map<String, Letter> synchHashMap = Collections.synchronizedMap(new HashMap<String, Letter>());
    private static final Logger logger = LoggerFactory.getLogger(AccountAction.class);
    private static final long serialVersionUID = 1L;
    private String url;                                    //页面的上一个跳转的url
    
    public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	// 收货地址数量限制
    private static final int addressCount = 20;
    /**
     * 用户的服务接口
     */
    @Autowired
    private AccountService accountService;
    /**
     * 账户余额积分的服务接口
     */
    @Autowired
    private AccountFinanceService accountFinanceService;
    /**
     * 订单的服务接口
     */
    @Autowired
    private OrderService orderService;
    /**
     * 配送地址的服务接口
     */
    @Autowired
    private AddressService addressService;
    /**
     * 商品的服务接口
     */
    @Autowired
    private ProductService productService;
    /**
     * 收藏的服务接口
     */
    @Autowired
    private FavoriteService favoriteService;//商品收藏夹
    /**
     * 发送邮件的服务接口
     */
    @Autowired
    private EmailService emailService;
    /**
     * 售后订单的服务接口
     */
    @Autowired
    private OrderRepairsService orderRepairsService;
    /**
     * 用户安全的服务接口
     */
    @Autowired
    private AccountSecurityService accountSecurityService;
    /**
     * redis服务接口
     */
    @Autowired
    private RedisCacheProvider redisCacheProvider;
    /**
     * 区域服务接口
     */
    @Autowired
    private AreaService areaService;
    @Autowired
    private SystemSetting systemSetting;
    @Autowired
    private SystemSettingService systemSettingService;
    @Autowired
    private OrderpayService orderpayService;

    // 登陆错误信息
    private static final String toLogin = "/account/login";							//转到登陆界面,forword方式 地址不变
    private static final String toLoginRedirect = "redirect:/account/login";		//转到登陆界面,getResponse().sendRedirect(arg0)方式 地址变化
    private static final String toIndex = "redirect:/";    //转到门户首页
    private static final String toregister = "/account/register";
    private static final String successMSG = "注册成功";

    @Override
    public AccountService getService() {
        return accountService;
    }

    /**
     * 用户注册
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "doRegister", method = RequestMethod.POST)
    @ResponseBody
    public String doRegister(Account e, ModelMap model) throws IOException 
    {
        if (StringUtils.isBlank(e.getId())) 
        {
            Letter letter = synchHashMap.get(e.getPhone());
            if (letter == null || !e.getCode().equals(letter.getCode())) 
            {
                String errorMsg = "验证码不正确或超时";
                model.addAttribute("errorMsg", errorMsg);
                return errorMsg;
            }
            synchHashMap.remove(e.getCode()); //验证完成清除验证码记录
            e.setPassword(MD5.md5(e.getPassword()));
            Account a = accountService.getUserInfoByPhones(e.getPhone());
            if (a != null) 
            {
                String errorMsg = "该用户已存在";
                model.addAttribute("errorMsg", errorMsg);
                return errorMsg;
            } 
            else 
            {
                Account account = accountService.selectAccount(e.getAccount());
                if (account != null) 
                {
                    String errorMsg = "用户名已存在!";
                    model.addAttribute("errorMsg", errorMsg);
                    return errorMsg;
                }
                int i = getService().insert(e);
                addAccountSecurity(e);//插入用户安全信息

                AccountFinance finance = new AccountFinance(); //生成用户钱包信息
                finance.setUserId(String.valueOf(i));
                accountFinanceService.insert(finance);
            }
        } 
        else 
        {
            // 修改密码
            throw new NullPointerException("用户编号不能注册！");
        }
        model.addAttribute("uid", e.getId());
        model.addAttribute("msg", "注册成功!");
        return successMSG;
    }

    /**
     * 添加用户安全
     */
    private int addAccountSecurity(Account e) {
        AccountSecurity accountSecurity = new AccountSecurity();
        accountSecurity.setUserId(e.getId());
        accountSecurity.setUserPassword(e.getPassword());
        accountSecurity.setUserPhone(e.getMobile());
        accountSecurity.setIsUpPwdSend("1");
        accountSecurity.setIsUpTelSend("1");
        int i = accountSecurityService.insert(accountSecurity);
        return i;
    }

    /**
     * 获取四位数字的验证码
     *
     * @return
     */
    private static String getNumberCode() {
        StringBuffer code = new StringBuffer("");
        for (int i = 0; i < 4; i++) {
            code.append((int) (Math.random() * 10));
        }

        return new String(code);
    }
    
    

    /**
     * 用户注册-获取短信验证码
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "getCode", method = RequestMethod.POST)
    public String getCode(String phone, ModelMap model) throws IOException 
    {
        SMSUtils smsUtils = new SMSUtils();
        if (StringUtils.isBlank(phone)) 
        {
            throw new NullPointerException("手机号不能为空！");
        } 
        else 
        {
            Account a = accountService.getUserInfoByPhones(phone);
            if (a != null) 
            {
                String errorMsg = "该用户已存在";
                model.addAttribute("errorMsg", errorMsg);
                return toregister;
                //throw new NullPointerException("用户已存在！");
            }
            String code = getNumberCode();
            String content = lettermodel.replace("#code#", code);
            smsUtils.send(phone, content + "【动漫商城】");
            Letter letter = new Letter();
            letter.setCode(code);
            letter.setContent(content);
            letter.setMobile(phone);
            letter.setCreateTime(new Date());
            synchHashMap.put(phone, letter);
        }
        return toregister;
    }

    /**
     * 用户注册--》再次发送邮件
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "sendEmailAgain", method = RequestMethod.POST)
    public String sendEmailAgain(String uid, ModelMap model) throws IOException {
        if (StringUtils.isBlank(uid)) {
            throw new NullPointerException("参数不正确！");
        }

        Account acc = accountService.selectById(uid);
        if (acc == null) {
            throw new NullPointerException("根据用户ID查询不到用户信息！");
        }

        accountService.sendEmail(acc, NotifyTemplate.email_reg);
        model.addAttribute("uid", acc.getId());
//		getResponse().sendRedirect(SystemManager.systemSetting.getWww()+"/account/checkEmail.html");
        return "redirect:/account/checkEmail.html";
    }

    /**
     * 转到邮箱验证提示页面
     * @return
     */
    @RequestMapping("checkEmail")
    public String checkEmail() {
        logger.info("checkEmail");
        return "/account/regsuccess";
    }

    /**
     * 转到忘记密码页面（邮箱找回）
     * @return
     */
    @RequestMapping("forget")
    public String forget() 
    {
        return "/account/forget";
    }

    /**
     * 转到忘记密码页面(手机号类)
     * @return
     */
    @RequestMapping("forgetByPhone")
    public String forgetByPhone() {
        return "/account/forgetByPhone";
    }

    /**
     * 通过邮箱找回密码
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "doForgetFromEmail", method = RequestMethod.POST)
    public String doForgetFromEmail(Account e, ModelMap model) throws Exception 
    {
    	AccountSecurity accountSecurityParam = new AccountSecurity();
    	accountSecurityParam.setEmail(e.getEmail());
    	AccountSecurity accountSecurity = accountSecurityService.selectOne(accountSecurityParam);
    	if(accountSecurity==null)
		{
			model.addAttribute("errorMsg", "<font color='red'>根据邮箱查询不到指定的会员信息，请联系管理员！</font>");
			return "/account/forget";
		}
    	Account a = new Account();
    	a.setId(accountSecurity.getUserId());
    	//根据邮箱查询用户信息
		Account acc = accountService.selectFrontOne(a);
		if(acc==null)
		{
			model.addAttribute("errorMsg", "<font color='red'>根据邮箱查询不到指定的会员信息，请联系管理员！</font>");
			return "/account/forget";
		}
		acc.setEmail(accountSecurity.getEmail());
        accountService.doForgetFromEmail(acc);
        //等待用户检查短信或邮件
        return "redirect:/account/waitUserCheck.html";
    }
    
    /**
     * 通过手机号找回密码
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "doForgetFromPhone", method = RequestMethod.POST)
    public String doForgetFromPhone(Account e, ModelMap model) throws Exception
    {
    	AccountSecurity accountSecurityParam = new AccountSecurity();
    	accountSecurityParam.setUserPhone(e.getPhone());
    	AccountSecurity accountSecurity = accountSecurityService.selectOne(accountSecurityParam);
    	if(accountSecurity==null)
		{
			model.addAttribute("errorMsg", "<font color='red'>根据手机号查询不到指定的会员信息，请联系管理员！</font>");
			return "/account/forget";
		}
    	Account a = new Account();
    	a.setId(accountSecurity.getUserId());
    	//根据邮箱查询用户信息
		Account acc = accountService.selectFrontOne(a);
		if(acc==null)
		{
			model.addAttribute("errorMsg", "<font color='red'>根据手机号查询不到指定的会员信息，请联系管理员！</font>");
			return "/account/forget";
		}
		acc.setPhone(accountSecurity.getUserPhone());
    	Letter letter = accountService.doForgetFromPhone(acc);
        synchHashMap.put(acc.getPhone(), letter);
        //等待用户检查短信或邮件
        model.addAttribute("phone",acc.getPhone());
        return "account/waitUserCheckphone";
    }
    
    /**
     * 验证找回密码的手机号的验证码
     * @return
     */
    @RequestMapping(value = "checkUserPhone", method = RequestMethod.POST)
    public String checkUserPhone(Account e, ModelMap model)
    {
    	 Letter letter = synchHashMap.get(e.getPhone());
         if (letter == null || !e.getCode().equals(letter.getCode())) 
         {
        	 synchHashMap.remove(e.getCode()); //验证完成清除验证码记录
             String errorMsg = "验证码不正确或超时";
             model.addAttribute("errorMsg", errorMsg);
             return errorMsg;
         }
         synchHashMap.remove(e.getCode()); //验证完成清除验证码记录
	        AccountSecurity accountSecurityParam = new AccountSecurity();
	     	accountSecurityParam.setUserPhone(e.getPhone());
	     	AccountSecurity accountSecurity = accountSecurityService.selectOne(accountSecurityParam);
	     	if(accountSecurity==null)
	 		{
	 			model.addAttribute("errorMsg", "<font color='red'>根据手机号查询不到指定的会员信息，请联系管理员！</font>");
	 			return "/account/forget";
	 		}
	     	Account a = new Account();
	     	a.setId(accountSecurity.getUserId());
	     	//根据邮箱查询用户信息
	 		Account acc = accountService.selectFrontOne(a);
	 		if(acc==null)
	 		{
	 			model.addAttribute("errorMsg", "<font color='red'>根据手机号查询不到指定的会员信息，请联系管理员！</font>");
	 			return "/account/forget";
	 		}
	 		acc.setPhone(accountSecurity.getUserPhone());
	 		model.addAttribute("e",acc);
         return "/account/reset";
    }
    
    /**
	 * 找回密码邮箱获得验证码
	 * @param e
	 * @return
	 */
	@RequestMapping("doForgetMailCheckNo")
	@ResponseBody
	public String doForgetMailCheckNo(Account e) {
		logger.error("e.getNewEmail() = " + e.getNewEmail());
		// 发送邮件到指定邮箱。
		sendMail(e.getNewEmail(), e, e.getVcode());
		return ("{\"ok\":\"发送成功!\"}");

	}
	
	/**
	 * 发送邮件
	 * @param email
	 * @param acc
	 * @param vcode
	 */
	private void sendMail(String email, Account acc, String vcode) 
	{
		Properties  properties = PropertiesUtil.findCommonPro("config.properties");
		final String url = properties.getProperty("mailUrl");
		final String apiUser = properties.getProperty("apiUser");
		final String apiKey = properties.getProperty("apiKey");
		final String from = properties.getProperty("from");
		final String fromname = properties.getProperty("fromname");
		final String templateInvokeName = properties.getProperty("templateInvokeName");

		Mail mail = new Mail();
		mail.setUrl(url);
		mail.setApiKey(apiKey);        
		mail.setApiUser(apiUser);
		mail.setSender(from);
		mail.setName(fromname);//发件人地址
		mail.setReceiver(email);    									   //收件人地址
		mail.setSubject("Anitoys提醒:" + acc.getAccount() + "验证邮箱设置"); //邮件主题
		mail.setTemplateInvokeName(templateInvokeName);
		mail.setMessage("尊敬的"
				+ acc.getAccount()
				+ ":您好, 您刚才在 Anitoys 申请了找回密码验证邮箱，请输入验证码<font color='red'>"
				+ vcode
				+ "</font>。"
				+ "</br>");
		try 
		{
			SendCloud.send_template(mail);
		}
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		//EmailUtils.send(mail);
	}

    @RequestMapping("waitUserCheck")
    public String waitUserCheck() {
        return "/account/waitUserCheck";
    }

    /**
     * ajax检查用户名称是否存在
     * @return
     * @throws IOException
     */
    @RequestMapping("checkAccountExist")
    @ResponseBody
    public String checkAccountExist(Account e) throws IOException 
    {
        if (StringUtils.isBlank(e.getAccount())) 
        {
            return ("{\"error\":\"用户名不能为空!\"}");
        }
        else 
        {
            Account acc = new Account();
            acc.setAccount(e.getAccount());
            if (accountService.selectCount(acc) == 0) 
            {
                return ("{\"error\":\"用户名不存在!\"}");
            } 
            else 
            {
                return ("{\"ok\":\"用户名输入正确!\"}");
            }
        }
    }

    /**
     * ajax检查密码是否正确
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("checkPassword")
    @ResponseBody
    public String checkPassword(Account e) throws IOException {
        if (StringUtils.isBlank(e.getPassword())) {
            return ("{\"error\":\"密码不能为空!\"}");
        } else {
            Account acc = new Account();
            acc.setPassword(MD5.md5(e.getPassword()));
            if (accountService.selectCount(acc) == 0) {
                return ("{\"error\":\"输入的密码不正确!\"}");
            } else {
                return ("{\"ok\":\"密码正确!\"}");
            }
        }
    }

    /**
     * ajax检查新邮箱不能和原邮箱一致
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("changeEmailCheck")
    @ResponseBody
    public String changeEmailCheck(Account e) throws IOException {
        if (StringUtils.isBlank(e.getNewEmail())) {
            return ("{\"error\":\"新邮箱不能为空!\"}");
        } else {
            Account acc = (Account) RequestHolder.getSession().getAttribute(FrontContainer.USER_INFO);
            if (acc == null || StringUtils.isBlank(acc.getAccount())) {
                return toLogin;
            }

            if (acc.getEmail().equals(e.getNewEmail())) {
                return ("{\"error\":\"新邮箱不能和原邮箱一致!\"}");
            } else {
                return ("{\"ok\":\"系统认为此邮箱可用!\"}");
            }
        }
    }

    /**
     * 转到登陆页面
     * @return
     */
    @RequestMapping("login")
    public String login() 
    {
    	systemSetting = systemSettingService.selectOne(new SystemSetting());
    	String loginUrl = systemSetting.getMy()+toLogin;
        url = RequestHolder.getRequest().getHeader("Referer");                  //获得前一页的URL
        if(url!=null && !url.equals(loginUrl)){
        	RequestHolder.getRequest().getSession().setAttribute("url", url);
        }
        logger.error("toLogin...");
        if (LoginUserHolder.getLoginAccount() != null) 
        {
        	String url = (String) RequestHolder.getRequest().getSession().getAttribute("url");
        	if(url!=null && !url.equals(loginUrl) && !url.equals(loginUrl+".html")){
        		return "redirect:"+url;
        	}
            return "redirect:"+systemSetting.getWww();
        }
        return toLogin;
    }

    /**
     * 转到注册页面
     *
     * @return
     */
    @RequestMapping("register")
    public String register() {
        logger.error("register...");
        if (LoginUserHolder.getLoginAccount() != null) {
        	systemSetting = systemSettingService.selectOne(new SystemSetting());
            return "redirect:"+systemSetting.getWww();
        }
        return "/account/register";
    }

    /**
     * 用户登陆
     *
     * @return
     */
    @RequestMapping("doLogin")
    public String doLogin(Account e, ModelMap model, RedirectAttributes flushAttrs) 
    {
    	url = RequestHolder.getRequest().getHeader("Referer");                  //获得前一页的URL
        logger.error("doLogin()...");
        if (LoginUserHolder.getLoginAccount() != null) 
        {
        	systemSetting = systemSettingService.selectOne(new SystemSetting());
        	return "redirect:"+systemSetting.getWww();
        }
        String errorMsg = "<font color='red'>帐号或密码错误!</font>";
        if (e.getAccount() == null || e.getAccount().trim().equals("")
                || e.getPassword() == null || e.getPassword().trim().equals(""))
        {
            model.addAttribute("errorMsg", errorMsg);
            logger.error("doLogin.errorMsg=" + errorMsg);
            return toLogin;
        }
        //用户中心登录获取令牌
        /*String url=properties.getProperty("authz.url");
        String host=properties.getProperty("authz.host");

        HttpMethod method;
        Map accountMap=null;
		try
		{
			method = UserInfoUtil.loginForAccount(url,e.getAccount(),e.getPassword(),e.getEmail(),e.getPhone());
			HttpClient http=new HttpClient();
	        http.getHostConfiguration().setHost(host,8080,"http");
	        //http.getHostConfiguration().setHost(host);
	        http.executeMethod(method);
	        String response=new String(method.getResponseBodyAsString().getBytes("gbk"));
	        if(response.contains("Error report")){
	        	model.addAttribute("errorMsg", "<font color='red'>请求超时!</font>");
				return toLogin;

	        }
	        accountMap = JsonUtil.jsonToMap(response);
	        if(accountMap.get("access_token")==null)
	        {
	        	model.addAttribute("errorMsg", accountMap.get("error_description"));
				return toLogin;
	        }
	        String expires_in = (String) accountMap.get("expires_in");
	        Date timeDate = new Date();
	        long t = timeDate.getTime();     //返回一个long型
	        accountMap.put("addTime", t);
		}
		catch (IOException e1)
		{
			e1.printStackTrace();
		}*/

        //用户验证
        e.setPassword(MD5.md5(e.getPassword()));
        String account = e.getAccount();
        String password = e.getPassword();
        e.clear();
        e.setAccount(account);
        e.setPassword(password);
        Account acc = accountService.selectFrontOne(e);

        if (acc == null) 
        {
            acc = accountService.getUserInfoByPhone(e);
            if (acc == null) 
            {
                model.addAttribute("errorMsg", errorMsg);
                return toLogin;
            }

        } 
        else if (acc.getFreeze().equals(Account.account_freeze_y)) 
        {
            if (StringUtils.isBlank(acc.getFreezeStartdate()) && StringUtils.isBlank(acc.getFreezeEnddate())) 
            {
                model.addAttribute("errorMsg", "<font color='red'>此账号已永久冻结!有疑问请联系站点管理员!</font>");
            } 
            else 
            {
                model.addAttribute("errorMsg", "<font color='red'>此账号已暂时冻结!有疑问请联系站点管理员!</font>");
            }
            return toLogin;
        }
//		else if(acc.getEmailIsActive().equals(Account.account_emailIsActive_n))
//		{
//			//邮箱未激活
//			errorMsg = "<font color='red'>此账号的邮箱尚未激活，请立即去激活邮箱！</font>";
//			model.addAttribute("errorMsg", errorMsg);
//			return toLogin;
//		}
        acc.setAccountId(acc.getId());
        errorMsg = null;
        acc.setLoginType(LoginTypeEnum.system);//登陆方式
        logger.info("acc.getId() = " + acc.getId());
        RequestHolder.getSession().setAttribute(FrontContainer.USER_INFO, acc);
        //更新用户最后登录时间
        e.clear();
        e.setId(acc.getId());
        e.setLastLoginTime("yes");
        e.setLastLoginIp(AddressUtils.getIp(RequestHolder.getRequest()));
        String address = null;
        try 
        {
            address = AddressUtils.getAddresses("ip=" + e.getLastLoginIp(), "utf-8");
        } 
        catch (Exception ex) 
        {
            ex.printStackTrace();
        }
        e.setLastLoginArea(address);
        accountService.update(e);
        
        OrderSimpleReport orderSimpleReport = orderService.selectOrdersSimpleReport(acc.getId());
        HttpSession session = RequestHolder.getRequest().getSession();
        session.setAttribute("waitOrder", orderSimpleReport.getOrderPassCount());
        model.addAttribute("orderSimpleReport", orderSimpleReport);
        
        systemSetting = systemSettingService.selectOne(new SystemSetting());
        return "redirect:"+url;
    }

    /**
     * @return
     */
    @RequestMapping("exit")
    public String exit() {
        logout();
        return "redirect:/account/login";
    }

    /**
     * 用户注销
     *
     * @return
     */
    @RequestMapping("logout")
    public String logout() {
        //清除用户session
        RequestHolder.getSession().setAttribute(FrontContainer.USER_INFO, null);

        //清除用户购物车缓存
        CartInfo cartInfo = (CartInfo) RequestHolder.getSession().getAttribute(FrontContainer.myCart);
        if (cartInfo != null) {
            cartInfo.clear();
        }
        RequestHolder.getSession().setAttribute(FrontContainer.myCart, null);

        //清除历史浏览记录
        LinkedHashMap<String, Product> history_product_map = (LinkedHashMap<String, Product>) RequestHolder.getSession().getAttribute(FrontContainer.history_product_map);
        if (history_product_map != null) {
            history_product_map.clear();
        }
        RequestHolder.getSession().setAttribute(FrontContainer.history_product_map, null);
        
        //清楚上一次浏览地址
        RequestHolder.getRequest().getSession().setAttribute("url",null);
        return toLogin;
    }

    /**
     * 分页查询商品收藏夹
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("favorite")
    public String favorite(ModelMap model) throws Exception {
        Account acc = (Account) LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }

        Favorite favorite = new Favorite();
        favorite.setAccount(acc.getAccount());
        PagerModel pager = selectPagerFavoriteList(favorite);

        if (pager != null && pager.getList() != null && pager.getList().size() > 0) {
            List<String> productIds = new LinkedList<String>();
            for (int i = 0; i < pager.getList().size(); i++) {
                Favorite ff = (Favorite) pager.getList().get(i);
//				productIds.add(ff.getProductID());
            }

            //根君商品ID集合加载商品信息：名称、价格、销量、是否上下架等
            Product p = new Product();
            p.setProductIds(productIds);
            List<Product> productList = productService.selectProductListByIds(p);

            //将查询出来的每一个商品对象挂到收藏夹对象上去
            if (productList != null && productList.size() > 0) {
                for (int i = 0; i < pager.getList().size(); i++) {
                    Favorite ff = (Favorite) pager.getList().get(i);
                    ff.setProduct(null);
                    for (int j = 0; j < productList.size(); j++) {
                        Product product = productList.get(j);
//						if(ff.getProductID().equals(product.getId()))
                        {
                            ff.setProduct(product);
                            break;
                        }
                    }
                    if (ff.getProduct() == null) {
                        //TODO 产品已经不存在
                    }
                }
            }
        }

//		selectLeftMenu = FrontContainer.user_leftMenu_favorite;
        model.addAttribute("pager", pager);
        return "/account/favorite";
    }

    private PagerModel selectPagerFavoriteList(Favorite fovorite) {
        int offset = 0;
        String pagerOffset = RequestHolder.getRequest().getParameter("pager.offset");
        if (StringUtils.isNotBlank(pagerOffset)) {
//			throw new NullPointerException();
            offset = (int) Double.parseDouble(pagerOffset);
        }
        if (offset < 0)
            offset = 0;
        fovorite.setOffset(offset);
        PagerModel servicesPager = favoriteService.selectPageList(fovorite);
        if (servicesPager == null) servicesPager = new PagerModel();
        // 计算总页数
        servicesPager.setPagerSize((servicesPager.getTotal() + servicesPager.getPageSize() - 1)
                / servicesPager.getPageSize());
        return servicesPager;
    }

    /**
     * ajax验证输入的字符的唯一性
     * @return
     * @throws IOException
     */
    @RequestMapping("checkUnique")
    @ResponseBody
    public String checkUnique(Account e) throws IOException 
    {
        logger.error("验证输入的字符的唯一性" + e);
        logger.error(e.getNickname());
        if (StringUtils.isNotBlank(e.getAccount())) 
        {
        	//验证用户名是否被占用
            logger.error("验证用户名是否被占用");
            String account = e.getAccount();
            e.clear();
            e.setAccount(account);
            if (accountService.selectCount(e) > 0) 
            {
                return ("{\"result\":\"error\"}");
            } 
            else 
            {
                return ("{\"result\":\"ok\"}");
            }
        } 
        else if (StringUtils.isNotBlank(e.getEmail())) 
        {
        	//验证邮箱是否被占用
            logger.error("验证邮箱是否被占用=" + e.getEmail());
            String email = e.getEmail();
            e.clear();
            e.setEmail(email);
            if (accountService.selectCount(e) > 0) 
            {
                return ("{\"result\":\"error\"}");
            } 
            else 
            {
                return ("{\"result\":\"ok\"}");
            }
        } 
        else if (StringUtils.isNotBlank(e.getPhone())) 
        {
        	//验证手机是否被占用
            logger.error("验证手机是否被占用=" + e.getPhone());
            e.clear();
            e.setPhone(e.getPhone());
            ;
            if (accountService.selectCount(e) > 0) 
            {
                return ("{\"result\":\"error\"}");
            } 
            else 
            {
                return ("{\"result\":\"ok\"}");
            }
        }
        else if (StringUtils.isNotBlank(e.getMobile())) 
        {
        	//验证手机是否被占用
            logger.error("验证手机是否被占用=" + e.getMobile());
            e.clear();
            e.setMobile(e.getMobile());
            if (accountService.selectCount(e) > 0) 
            {
                return ("{\"result\":\"error\"}");
            } 
            else 
            {
                return ("{\"result\":\"ok\"}");
            }
        }
        if (e != null) 
        {
            e.clear();
        }
        return null;
    }
    
    
    /**
	 * ajax验证输入的字符的唯一性
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("unique")
	@ResponseBody
	public String unique(Account e) throws IOException
	{
		logger.error("验证输入的字符的唯一性"+e);
		logger.error(e.getNickname());
		if(StringUtils.isNotBlank(e.getNickname()))
		{
			//验证昵称是否被占用
			logger.error("验证昵称是否被占用");
			String nickname = e.getNickname();
			e.clear();
			e.setNickname(nickname);
			if (accountService.selectCount(e)>0){
				return ("{\"error\":\"昵称已经被占用!\"}");
			}else{
				return ("{\"ok\":\"昵称可以使用!\"}");
			}
		}
		else if(StringUtils.isNotBlank(e.getAccount()))
		{
			//验证用户名是否被占用
			logger.error("验证用户名是否被占用");
			String account = e.getAccount();
			e.clear();
			e.setAccount(account);
			if (accountService.selectCount(e)>0){
				return ("{\"error\":\"用户名已经被占用!\"}");
			}else{
				return ("{\"ok\":\"用户名可以使用!\"}");
			}
		}
		else if(StringUtils.isNotBlank(e.getEmail()))
		{
			//验证邮箱是否被占用
			logger.error("验证邮箱是否被占用="+e.getEmail());
			String email = e.getEmail();
			e.clear();
			e.setEmail(email);
			if (accountService.selectCount(e) > 0){
				return ("{\"error\":\"邮箱已经被占用!\"}");
			}else{
				return ("{\"ok\":\"邮箱可以使用!\"}");
			}
		}
		else if(StringUtils.isNotBlank(e.getVcode()))
		{
			//验证验证码输入的是否正确
			logger.error("检查验证码输入的是否正确"+e.getVcode());
			String validateCode = RequestHolder.getSession().getAttribute(FrontContainer.validateCode).toString();
			logger.error("validateCode=" + validateCode);
			if(validateCode.equalsIgnoreCase(e.getVcode())){
				return ("{\"ok\":\"验证码输入正确!\"}");
			}else{
				return ("{\"error\":\"验证码输入有误!\"}");
			}
//			vcode = null;
		}
		else if(StringUtils.isNotBlank(e.getPassword()))
		{
			//验证原始密码输入是否正确
			logger.error("验证原始密码输入是否正确"+e.getPassword());
			Account acc = LoginUserHolder.getLoginAccount();
			if(StringUtils.isNotBlank(e.getPassword()) && MD5.md5(e.getPassword()).equals(acc.getPassword()))
			{
				return ("{\"ok\":\"原密码输入正确!\"}");
			}
			else
			{
				return ("{\"error\":\"原密码输入有误!\"}");
			}
		}
		if(e!=null)
		{
			e.clear();
		}
		return null;
	}

    /**
     * 查看个人信息
     *
     * @return
     */
    @RequestMapping("account")
    public String account(ModelMap model, Account e) {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }

//		selectLeftMenu = "user";
        e = accountService.selectById(acc.getId());
//		setSelectMenu(FrontContainer.not_select_menu);//设置主菜单为不选中

//		getSession().setAttribute(FrontContainer.WEB_USER_INFO,e);

        //查询未读信件的数量
//		Letters letter = new Letters();
//		letter.setAccount(acc.getAccount());
//		int notReadLetters = lettersService.getCount(letter);
//		logger.error("notReadLetters="+notReadLetters);
//		acc.setNotReadLetters(notReadLetters);
        model.addAttribute("e", e);

        Map<String, Area> areaMap = loadArea();
        model.addAttribute("provinces", areaMap.values());
        if (StringUtils.isNotBlank(e.getProvince()) && areaMap.get(e.getProvince()) != null) {
            model.addAttribute("cities", areaMap.get(e.getProvince()).getChildren());
        } else {
            model.addAttribute("cities", new ArrayList<Area>());
        }
        return "/account/account";
    }

    /**
     * 修改个人信息
     *
     * @return
     */
    @RequestMapping("saveSetting")
    public String saveSetting(ModelMap model, Account e) {
        Account account = LoginUserHolder.getLoginAccount();
        if (account == null || StringUtils.isBlank(account.getAccount())) {
            return toLogin;
        }
        logger.error("saveSetting.....{}", e);
//		logger.error("sex="+sex);
        e.setId(account.getId());
        accountService.update(e);
//		Account acc = (Account) getSession().getAttribute(FrontContainer.USER_INFO);
//		acc.setSign(e.getSign());
//		acc.setMyself(e.getMyself());
//		acc.setSex(e.getSex());

        e.clear();
        account = accountService.selectById(account.getId());
        RequestHolder.getSession().setAttribute(FrontContainer.USER_INFO, account);
//		return "saveSetting";
        return account(model, e);
    }

    private boolean requireLogin() throws NullPointerException {
        Account account = LoginUserHolder.getLoginAccount();
        if (account == null || StringUtils.isBlank(account.getAccount())) {
            return true;
        }
        return false;
    }

    /**
     * 配送地址管理
     *
     * @return
     */
    @RequestMapping("address")
    public String address(ModelMap model, Address address) {
        Account account = LoginUserHolder.getLoginAccount();
        if (account == null || StringUtils.isBlank(account.getAccount())) {
            return toLogin;
        }
//		selectLeftMenu = "address";
        address.setAccountId(account.getAccount());
        List<Address> addressList = addressService.selectList(address);
        model.addAttribute("address", address);
        model.addAttribute("addressList", addressList);
        Map<String, Area> areaMap = loadArea();
        model.addAttribute("provinces", areaMap.values());
        List<Area> cities = new ArrayList<Area>();
        List<Area> areas = new ArrayList<Area>();
        if (StringUtils.isNotBlank(address.getProvince()) && areaMap.get(address.getProvince()) != null) {
            cities = areaMap.get(address.getProvince()).getChildren();
        }
        model.addAttribute("cities", cities);
        String area = address.getArea();
        for (Area a : cities) {
            if (a.getCode().equals(area)) {
                areas = a.getChildren();
                break;
            }
        }
        //TODO 缓存的地址只有二级，没有区县
        model.addAttribute("areas", areas);
        return "/account/address";
    }

    /**
     * 增加配送地址
     *
     * @return
     */
    @RequestMapping("saveAddress")
    public String saveAddress(ModelMap model, Address address) {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
//		selectLeftMenu = "address";

        //需要将省市区的代号换成中文，插入到pcadetail字段里面去，显示的时候方便。
        StringBuilder pcadetail = new StringBuilder();
        Map<String, Area> areaMap = loadArea();
        Area sheng = areaMap.get(address.getProvince());//省
        pcadetail.append(sheng.getName());

        for (int i = 0; i < sheng.getChildren().size(); i++) {
            Area shi = sheng.getChildren().get(i);//市
            if (shi.getCode().equals(address.getCity())) {

                pcadetail.append(" ").append(shi.getName());

                for (int j = 0; j < shi.getChildren().size(); j++) {
                    Area qu = shi.getChildren().get(j);//区
                    if (qu.getCode().equals(address.getArea())) {
                        pcadetail.append(" ").append(qu.getName());
                        break;
                    }
                }

                break;
            }
        }

        address.setPcadetail(pcadetail.toString());

        address.setAccountId(acc.getAccount());
        if (StringUtils.isBlank(address.getId())) {
            addressService.insert(address);
        } else {
            addressService.update(address);
        }
        address.clear();
        return address(model, address);
    }

    /**
     * 删除指定的配送地址
     *
     * @return
     */
    @RequestMapping("deleteAddress")
    public String deleteAddress(ModelMap model, Address address) {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
//		selectLeftMenu = "address";
        String id = address.getId();
        if (StringUtils.isBlank(id)) {
            throw new NullPointerException("id is null!");
        }
        Address add = new Address();
        add.setId(id);
        addressService.delete(add);

        return address(model, address);
    }

    /**
     * 编辑指定的配送地址
     *
     * @return
     */
    @RequestMapping("editAddress")
    public String editAddress(ModelMap model, Address address) {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
//		selectLeftMenu = "address";
        String id = address.getId();
        if (StringUtils.isBlank(id)) {
            throw new NullPointerException("id is null!");
        }
        address = addressService.selectById(id);

        //获取区域列表
        if (StringUtils.isNotBlank(address.getArea())) {
//			address.getArea()
            Map<String, Area> areaMap = loadArea();
            Area area = areaMap.get(address.getProvince());
            if (area != null && area.getChildren() != null && area.getChildren().size() > 0) {
                for (int i = 0; i < area.getChildren().size(); i++) {
                    Area city = area.getChildren().get(i);
                    if (city.getCode().equals(address.getCity())) {

                        logger.error("address.getCity()=" + address.getCity());
                        logger.error(city.toString());
                        address.setAreaList(city.getChildren());
                        break;
                    }
                }
            }
        }

        return address(model, address);
    }

    /**
     * 我的订单列表
     * update 2015-11-29 jiangyzh 修改按订单status状态查询订单
     * @return
     * @throws Exception
     */
    @RequestMapping("orders")
    public String orders(ModelMap model) throws Exception
    {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) 
        {
            return toLogin;
        }
        int productCount = productService.selectProductCount();
        Account newAcc = accountService.getUserInfoPoint(acc.getId());
        if (StringUtils.isBlank(newAcc.getHead())) 
        {
            newAcc.setHead("attached/image/head/default.png");
        }
        model.addAttribute("productCount", productCount);
        model.addAttribute("newAcc", newAcc);
        Map paramMap = new HashMap();
        String status = RequestHolder.getRequest().getParameter("status");
        logger.debug("按订单状态筛选参数status -->:" + status);
        if (!StringUtils.isBlank(status)) 
        {
            //订单状态：待确认收货（sign：已签收；file:已归档）
            if ("dsh".equals(status)) 
            {
                status = " and status in ('" + com.soloyogame.anitoys.db.commond.Order.order_status_stay + "','" + com.soloyogame.anitoys.db.commond.Order.order_status_sign + "','" + com.soloyogame.anitoys.db.commond.Order.order_status_send + "') ";
            }
            //订单状态：待付款（订单支付状态paystatus为n:未支付，且订单状态status不为cancel:已取消）
            else if ("dfk".equals(status))
            {
                status = " and status = '" + com.soloyogame.anitoys.db.commond.Order.order_status_init + "' AND passStatus IS NULL AND initStatus IS NULL AND expiredTime IS NULL";
//				status = "'init','pass','send','sign','file','finish'";
//				paramMap.put("paystatus", "n");
            }
            //订单状态：待补款（订单支付状态paystatus为n:未支付，且订单状态status不为cancel:已取消）
            else if ("dbk".equals(status)) 
            {
                status = " and status in ('" + com.soloyogame.anitoys.db.commond.Order.order_status_pass + "') AND passStatus IS NULL AND initStatus IS NULL AND expiredTime IS NULL";
            }
            //订单状态：失效（订单状态status为cancel:已取消）
            else if ("cancel".equals(status)) 
            {
                status = " and  ( status='" + com.soloyogame.anitoys.db.commond.Order.order_status_cancel + "' OR passStatus IS NOT NULL OR initStatus IS NOT NULL OR expiredTime IS NOT NULL )";
            }
            //订单状态：待评价（订单状态为finish：交易完成，且评价表中没有该订单的评价记录）
            else if ("finish".equals(status)) 
            {
                status = " and status='" + com.soloyogame.anitoys.db.commond.Order.order_status_file + "' ";
            }
        }
        logger.debug(paramMap.get("paystatus") + "--paystatus--------------------");
        paramMap.put("account", acc.getId());
        paramMap.put("status", status);
        logger.debug(paramMap.get("status") + "--status--------------------");
        PagerModel pager = getMyOrders(paramMap);
        model.addAttribute("pager", pager);

        //查询汇总
        OrderSimpleReport orderSimpleReport = orderService.selectOrdersSimpleReport(acc.getId());
        model.addAttribute("orderSimpleReport", orderSimpleReport);
        logger.error("orderSimpleReport=" + orderSimpleReport);
        return "/account/orders";
    }

    /**
     * 分页查询订单集合
     *
     * @return
     * @throws Exception
     */
    private PagerModel selectMyOrders(Map paramMap) throws Exception {
        int offset = 0;
        if (RequestHolder.getRequest().getParameter("pager.offset") != null) {
            offset = Integer
                    .parseInt(RequestHolder.getRequest().getParameter("pager.offset"));
        }
        if (offset < 0)
            offset = 0;

        PagerModel pager = new PagerModel();
        Order order = new Order();
        order.setAccount((String) paramMap.get("account"));
        order.setStatus((String) paramMap.get("status"));
        order.setPaystatus((String) paramMap.get("paystatus"));
        (order).setOffset(offset);
        pager = orderService.selectFrontPageList(order);
        if (pager == null) pager = new PagerModel();
        // 计算总页数
        pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1)
                / pager.getPageSize());

//		selectListAfter();
        pager.setPagerUrl("orders");
        return pager;
    }

    /**
     * 分页获取我的订单列表，首页分页查询订单集合，然后把查询到的ID集合仍到一个多表联合的查询里面，查询出更多的信息。分页显示用户的订单只用一个SQL貌似不好搞的。想到好办法再去优化。
     * @throws Exception
     */
    private PagerModel getMyOrders(Map paramMap) throws Exception {
        //分页查询订单ID集合
//		super.selectList();
        //1、分页查询订单集合
        PagerModel pager = selectMyOrders(paramMap);
        //根据上面查询出来的ID集合，多表联合查询出订单和订单明细数据
        List<Order> ordersTemp = pager.getList();
        List<String> ids = new LinkedList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < ordersTemp.size(); i++) 
        {
            Order orderItem = ordersTemp.get(i);
            //时间转换成可以阅读的格式
            ids.add(orderItem.getId());
            //根据订单ID得到订单的支付信息
            Orderpay orderpay = new Orderpay();
            double alreadyPayAmount = 0.00;
            Orderpay orderPayParam = new Orderpay();
            orderPayParam.setOrderid(orderItem.getId());
            orderPayParam.setPaystatus("y");
            List<Orderpay> orderPayList = orderpayService.selectList(orderPayParam);//得到订单的支付记录
            orderItem.setOrderpayList(orderPayList);
            for (Orderpay orderpay2 : orderPayList) 
            {
            	alreadyPayAmount = alreadyPayAmount+orderpay2.getPayamount();
			}
            DecimalFormat df = new DecimalFormat("0.00");
            orderpay.setAlreadyPayAmount(df.format(alreadyPayAmount));
            orderItem.setOrderpay(orderpay);
        }

        Order order = new Order();
        order.clear();
        order.setAccount((String) paramMap.get("account"));
        order.setQueryOrderIDs(ids);
        //2、查询指定订单集合的所有订单项集合，然后内存中对订单项进行分组
        List<Order> myOrders = orderService.selectFrontList(order);
        if (myOrders != null && myOrders.size() > 0) {
            for (int i = 0; i < ordersTemp.size(); i++) {
                Order orderItem = ordersTemp.get(i);
                logger.debug("-----------------order 转换前t_order.status = " + orderItem.getStatus());
                //失效订单状态处理
                logger.debug("-----------------失效订单状态处理 InitStatus = " + orderItem.getInitStatus() + "  PassStatus = " + orderItem.getPassStatus() + "  ExpiredTime = " + orderItem.getExpiredTime());
                if (!StringUtils.isBlank(orderItem.getInitStatus()) || !StringUtils.isBlank(orderItem.getPassStatus()) || orderItem.getExpiredTime() != null) {
                    orderItem.setStatus(com.soloyogame.anitoys.db.commond.Order.order_status_cancel);
                }
                logger.debug(orderItem.getCustomerAddress() + "-----------------order 转换后t_order.status = " + orderItem.getStatus());

                if (!StringUtils.isBlank(orderItem.getCustomerAddress()) && orderItem.getCustomerAddress().indexOf("http://") <= 0) {
                    orderItem.setCustomerAddress(orderItem.getCustomerAddress());
                }

                int j = 0;
                for (Iterator<Order> it = myOrders.iterator(); it.hasNext(); ) {
                    Order orderdetail = it.next();
//					logger.error("orderdetail.getId()="+orderdetail.getId());
//					logger.error("orderItem.getId()="+orderItem.getId());
                    if (orderdetail.getId().equals(orderItem.getId())) {
                        orderItem.setIndextotalNum(j + 1);
                        orderdetail.setIndex(j);
                        //失效订单状态处理
                        if (!StringUtils.isBlank(orderItem.getStatus()) && com.soloyogame.anitoys.db.commond.Order.order_status_cancel.equals(orderItem.getStatus())) {
                            orderdetail.setStatus(com.soloyogame.anitoys.db.commond.Order.order_status_cancel);
                        }
                        orderdetail.setCreatedate(DateTimeUtil.getDateTimeString(sdf.parse(orderItem.getCreatedate())));
                        orderdetail.setPayTime(orderItem.getPayTime());
                        if (StringUtils.isBlank(orderItem.getClosedComment())) {
                            orderdetail.setClosedComment("n");
                        }
                        if (StringUtils.isBlank(orderItem.getIsComment())) {
                            orderdetail.setIsComment("0");
                        }
                        if (!StringUtils.isBlank(orderdetail.getSpecInfo()) && orderdetail.getSpecInfo().indexOf(",") > 0) {
                            orderdetail.setSpecInfo(orderdetail.getSpecInfo().replace(",", "<br />"));
                            logger.debug("-------SpecInfo----------" + orderdetail.getSpecInfo());
                        }
                        orderItem.getOrders().add(orderdetail);
                        it.remove();
                        j++;
                    }
                }
                logger.debug("order.id = " + orderItem.getId() + "-----------------IndextotalNum = " + orderItem.getIndextotalNum());
            }
        }

        return pager;
    }

    /**
     * 转到修改密码
     * @return
     */
    @RequestMapping("topwd")
    public String topwd(ModelMap model, @ModelAttribute("e") Account e) {
        if (LoginUserHolder.getLoginAccount() == null) {
            return toLoginRedirect;
        }
        return "/account/topwd";
    }

    /**
     * 修改密码
     *
     * @return
     */
    @RequestMapping("changePwd")
    public String changePwd(ModelMap model, @ModelAttribute("e") Account e, RedirectAttributes flushAttrs) {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }

        if (StringUtils.isBlank(e.getNewPassword())
                || StringUtils.isBlank(e.getNewPassword2())
                || StringUtils.isBlank(e.getPassword())
                || !e.getNewPassword2().equals(e.getNewPassword())) {
            throw new NullPointerException();
        }
        e.setPassword(MD5.md5(e.getNewPassword()));
        e.setId(acc.getId());
        accountService.update(e);
        flushAttrs.addFlashAttribute("errorMsg", "修改密码成功！");
        //重新缓存密码数据
        acc.setPassword(e.getPassword());
        e.clear();
        AccountSecurity ae = new AccountSecurity();
        ae.setUserId(acc.getId());
        AccountSecurity accSecurity = accountSecurityService.selectOne(ae);
        if (accSecurity != null) {
            if (StringUtils.isNotBlank(accSecurity.getEmail()) && "1".equals(accSecurity.getIsUpPwdSend())) {
                sendRegisterSucMail(accSecurity.getEmail(), acc);
            }
        }
        return "redirect:/account/changePwdSuccess";
    }

    /**
     * 发送修改密码成功邮件
     * @param email
     * @param acc
     */
    public void sendRegisterSucMail(String email, Account acc) {
        Properties properties = PropertiesUtil.findCommonPro("conf.properties");
        String host = properties.getProperty("mail.host");
        String sender = properties.getProperty("mail.sender");
        String userName = properties.getProperty("mail.username");
        String password = properties.getProperty("mail.password");
        Mail mail = new Mail();
        mail.setHost(host); // 设置邮件服务器163的
        mail.setSender(sender);
        mail.setReceiver(email); // 接收人
        mail.setUsername(userName); // 登录账号
        mail.setPassword(password); // 发件人邮箱的登录密码
        mail.setSubject("Anitoys提醒:" + acc.getAccount() + "修改密码");
        mail.setMessage("尊敬的"
                + acc.getAccount()
                + ": 您好, 您的密码已修改成功，请重新登录！"
                + "</br>");
        EmailUtils.send(mail);
    }

    @RequestMapping("changePwdSuccess")
    public String changePwdSuccess() {
        return "/account/changePwdSuccess";
    }

    /**
     * 设置选中的
     *
     * @return
     */
    @RequestMapping("setAddressDefault")
    @ResponseBody
    public String setAddressDefault(ModelMap model, Address e) {
        String id = e.getId();
        if (StringUtils.isBlank(id)) {
            throw new NullPointerException("默认地址ID不能为空！");
        }

        Account account = LoginUserHolder.getLoginAccount();
        if (account == null || StringUtils.isBlank(account.getAccount())) {
            throw new NullPointerException("账号不能为空！");
        }
        Address address = new Address();
        address.setId(id);
        address.setIsdefault("y");
        address.setAccountId(account.getAccount());
        addressService.setAddressDefault(address);
        return null;
    }

    /**
     * 根据省份编码获取城市列表
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("selectCitysByProvinceCode")
    @ResponseBody
    public String selectCitysByProvinceCode() throws IOException {
        logger.error("selectCitysByProvinceCode...");
        String provinceCode = RequestHolder.getRequest().getParameter("provinceCode");
        logger.error("selectCitysByProvinceCode...provinceCode=" + provinceCode);
        if (StringUtils.isBlank(provinceCode)) {
            throw new NullPointerException("provinceCode is null");
        }

        Map<String, Area> areaMap = loadArea();
        if (areaMap != null && areaMap.size() > 0) {
            Area areaInfo = areaMap.get(provinceCode);

            logger.error("areaInfo = " + areaInfo);

            if (areaInfo != null && areaInfo.getChildren() != null && areaInfo.getChildren().size() > 0) {
                String jsonStr = JSON.toJSONString(areaInfo.getChildren());
                logger.error("jsonStr=" + jsonStr);
                return (jsonStr);
            }
        }

        return ("{}");
    }

    /**
     * 根据城市编码获取区域列表
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("selectAreaListByCityCode")
    @ResponseBody
    public String selectAreaListByCityCode() throws IOException {
        logger.error("selectAreaListByCityCode...");
        String provinceCode = RequestHolder.getRequest().getParameter("provinceCode");
        String cityCode = RequestHolder.getRequest().getParameter("cityCode");
        logger.error("selectAreaListByCityCode...provinceCode=" + provinceCode + ",cityCode=" + cityCode);
        if (StringUtils.isBlank(provinceCode) || StringUtils.isBlank(cityCode)) {
            throw new NullPointerException("provinceCode or cityCode is null");
        }

        Map<String, Area> areaMap = loadArea();
        if (areaMap != null && areaMap.size() > 0) {
            Area city = areaMap.get(provinceCode);

            logger.error("areaInfo = " + city);

            if (city != null && city.getChildren() != null && city.getChildren().size() > 0) {
                for (int i = 0; i < city.getChildren().size(); i++) {
                    Area item = city.getChildren().get(i);
                    if (item.getCode().equals(cityCode)) {
                        if (item.getChildren() != null && item.getChildren().size() > 0) {
                            String jsonStr = JSON.toJSONString(item.getChildren());
                            logger.error("jsonStr=" + jsonStr);
                            return (jsonStr);
                        }
                    }
                }
            }
        }

        return ("{}");
    }


    /**
     * 用户使用邮件重置密码
     * @return
     */
    @RequestMapping("reset")
    public String reset(ModelMap model, @ModelAttribute("e") Account account) 
    {
        checkSendEmail(model, account);
        return "/account/reset";
    }

    /**
     * 系统发出邮件后，用户访问邮件中的URL地址，此方法检查该地址的有效性和时间的有效性
     */
    private Email checkSendEmail(ModelMap model, Account account) 
    {
        String sign = RequestHolder.getRequest().getParameter("sign");
        if (StringUtils.isBlank(sign)) 
        {
            throw new NullPointerException("参数非法!");
        }

        //查询邮件是否是本系统所发出的
        Email email = new Email();
        email.setSign(sign);
        email = emailService.selectOne(email);
        if (email == null) 
        {
            throw new NullPointerException("非法请求！");
        }

        if (email.getStatus().equals(Email.email_status_y)) 
        {
            model.addAttribute(FrontContainer.reset_password_email_timeout, "当前连接已失效！");
            return null;
        }
        account.setAccount(email.getAccount());
        //检查此邮件是否过期
        long time1 = Long.valueOf(email.getStarttime());
        long time2 = new Date().getTime();
        long time3 = Long.valueOf(email.getEndtime());
        if (time2 > time1 && time2 < time3) 
        {
            //更新邮件状态为已失效
            Email email2 = new Email();
            email2.setStatus(email.email_status_y);
            email2.setId(email.getId());
            emailService.update(email2);

            //允许修改密码
            return email;
        } 
        else 
        {
            logger.error("邮件已过期！");
            model.addAttribute(FrontContainer.reset_password_email_timeout, "当前连接已失效！");
        }
        return null;
    }

    /**
     * 通过邮件重置密码
     * @return
     * @throws IOException
     */
    @RequestMapping("doReset")
    public String doReset(ModelMap model, Account e) throws IOException 
    {
        logger.error("doReset...");
        if (StringUtils.isBlank(e.getAccount()) || StringUtils.isBlank(e.getPassword()) || StringUtils.isBlank(e.getPassword2())) 
        {
            throw new NullPointerException("请求非法！");
        }

        if (!e.getPassword().equals(e.getPassword2())) 
        {
//			getRequest().setAttribute(FrontContainer.show_user_option_error, "两次输入的密码不一致！");
            throw new RuntimeException("两次输入的密码不一致！");
        }
        logger.error("doReset...e.getPassword() = " + e.getPassword());
        Account acc = new Account();
        acc.setAccount(e.getAccount());
        acc.setPassword(MD5.md5(e.getPassword()));
        accountService.updatePasswordByAccount(acc);
        return "redirect:/account/resetSuccess";
//		return "resetSuccess";
    }

    @RequestMapping("resetSuccess")
    public String resetSuccess() {
        return "/account/resetSuccess";
    }

    /**
     * 转到修改邮箱页面
     * @return
     */
    @RequestMapping("changeEmail")
    public String changeEmail() {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLoginRedirect;
        }
        return "/account/changeEmail";
    }

    /**
     * 修改邮箱
     * @return
     * @throws Exception
     */
    @RequestMapping("doChangeEmail")
    public String doChangeEmail(Account e) throws Exception 
    {
        logger.error("e.getNewEmail() = " + e.getNewEmail());
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) 
        {
            return toLogin;
        }

        logger.error("doChangeEmail..");
        e.setId(acc.getId());
        if (StringUtils.isBlank(e.getPassword()) || StringUtils.isBlank(e.getNewEmail())) 
        {
            throw new NullPointerException("非法请求！");
        }
        if (!MD5.md5(e.getPassword()).equals(acc.getPassword())) 
        {
            //前台AJAX检查密码出问题了，后台来处理前端的不足
            throw new RuntimeException("出现错误，请联系系统管理员！");
        }
        //发送邮件到指定邮箱。
        acc.setNewEmail(e.getNewEmail());
        accountService.sendEmail(acc, NotifyTemplate.email_change_email);
        acc.setNewEmail(null);
        return "redirect:/account/changeEmailWait.html";
    }

    @RequestMapping("changeEmailWait")
    public String changeEmailWait() 
    {
        logger.error("changeEamilWait..");
        return "account/changeEmailWait";
    }

    /**
     * 修改邮箱--->用户登陆邮箱后点击邮件---->激活邮箱---->调用此方法
     *
     * @return
     */
    @RequestMapping("active")
    public String active(ModelMap model, Account account) {
        logger.error("active...");
        String sign = RequestHolder.getRequest().getParameter("sign");
        if (StringUtils.isBlank(sign)) {
            throw new NullPointerException("非法请求！");
        }
        Email email = checkSendEmail(model, account);
        if (email != null) {
            Account acc = new Account();
            acc.setEmail(email.getNewEmail());
            acc.setAccount(email.getAccount());
            accountService.updateEmailByAccount(acc);

            //修改邮箱成功后，更新session缓存中数据
            acc = LoginUserHolder.getLoginAccount();
            if (acc != null && StringUtils.isNotBlank(acc.getAccount())) {
                acc.setEmail(email.getNewEmail());
            }

            email = new Email();
            email.setStatus(email.email_status_n);
            email.setPageMsg("恭喜：新邮箱已激活！");
            model.addAttribute(FrontContainer.reset_password_email_timeout, email);
        } else {
            email = new Email();
            email.setStatus(email.email_status_y);
            email.setPageMsg("当前连接已失效！");
            model.addAttribute(FrontContainer.reset_password_email_timeout, email);
        }
        return "/account/active";
    }

    /**
     * 激活账号的邮件的回调
     *
     * @return
     */
    @RequestMapping("activeAccount")
    public String activeAccount(HttpServletRequest request) {
        logger.error("active...");
        String sign = request.getParameter("sign");
        if (StringUtils.isBlank(sign)) {
            throw new NullPointerException("非法请求！");
        }

        //查询邮件是否是本系统所发出的
        Email email = new Email();
        email.setSign(sign);
        email = emailService.selectOne(email);
        if (email == null) {
            throw new NullPointerException("非法请求！");
        }

        if (email.getStatus().equals(Email.email_status_y)) {
            request.setAttribute("LinkInvalid", "链接已失效！");
            return "/account/reg_success_active_result";
        }

        Account acc = new Account();
        acc.setAccount(email.getAccount());
        acc = accountService.selectOne(acc);
        if (acc == null) {
            throw new NullPointerException("非法请求！");
        }

        Account acc2 = new Account();
        acc2.setId(acc.getId());
        acc2.setEmailIsActive(Account.account_emailIsActive_y);
        accountService.updateDataWhenActiveAccount(acc2, acc.getAccount());

        return "/account/reg_success_active_result";
    }

    /**
     * 个人资料
     *
     * @return
     * @throws Exception
     * @author yantao by 20151202
     */
    @RequestMapping("myData")
    public String myData(ModelMap model) throws Exception {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        List<Product> productList = new ArrayList<Product>();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        CartInfo cartInfo = null;
        if (acc == null) {
            cartInfo = (CartInfo) redisCacheProvider.get("myCart");
        } else {
            cartInfo = (CartInfo) redisCacheProvider.get("user_" + acc.getId() + "Cart");
        }
        if (cartInfo != null) {
            productList = cartInfo.getProductList();
        } else {
            cartInfo = new CartInfo();
        }
        int productCount = productService.selectProductCount();

        model.addAttribute("cartInfo", cartInfo);
        model.addAttribute("productCount", productCount);
        model.addAttribute("productList", productList);

        /**
         * 查询用户信息
         */
        Account myData = accountService.selectById(acc.getId());
        if (myData == null) {
            myData = new Account();
            myData.setSex("m");
        }
        model.addAttribute("myData", myData);
        /**
         * 获取默认地址信息
         */
        Map<String, Area> areaMap = loadArea();

        List<Area> cities = new ArrayList<Area>();
        List<Area> areas = new ArrayList<Area>();
        if (null != myData.getProvince() && null != areaMap.get(myData.getProvince()) && StringUtils.isNotBlank(myData.getProvince())) {
            cities = areaMap.get(myData.getProvince()).getChildren();
        }
        String area = myData.getCity();
        for (Area a : cities) {
            if (a.getCode().equals(area)) {
                areas = a.getChildren();
                break;
            }
        }
        model.addAttribute("provinces", areaMap.values()); //身份
        model.addAttribute("cities", cities);//城市
        model.addAttribute("areas", areas);//区县
        logger.error("myData=" + myData);
        logger.error("myData=" + myData.getTrueName());
        return "/account/myData";
    }

    /**
     * 个人资料baocun
     *
     * @return
     * @throws Exception
     * @author yantao by 20151202
     */
    @RequestMapping(value = "saveMyData", method = RequestMethod.POST)
    public String saveMyData(HttpServletRequest request, @ModelAttribute("account") Account account, RedirectAttributes flushAttrs) throws Exception {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        account.setId(acc.getId());
        if (account.getAccount() != null && account.getAccount() != "") {
            //判断是否唯一  存在跳转修改失败页面
            Account e = new Account();
            e.setNotId(acc.getId());
            e.setAccount(account.getAccount());
            e = accountService.selectOne(e);
            if (e != null) {
                return "redirect:/account/changeAccountError";
            } else {
                account.setIsUpdate("y");
            }
        }
        /**
         * 修改个人信息
         */
        accountService.updateFront(account);

        return "redirect:/account/changeAccountSuccess";
    }

    @RequestMapping("changeAccountError")
    public String changeAccountError(ModelMap model) throws Exception {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        int productCount = productService.selectProductCount();
        model.addAttribute("productCount", productCount);
        return "/account/changeAccountError";
    }

    @RequestMapping("changeAccountSuccess")
    public String changeAccountSuccess(ModelMap model) throws Exception {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        int productCount = productService.selectProductCount();
        model.addAttribute("productCount", productCount);
        return "/account/changeAccountSuccess";
    }


    private String getDateStr() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String time = format.format(date);
        return time;
    }


    /**
     * 头像设置
     *
     * @return
     * @throws Exception
     * @author yantao by 20151202
     */
    @RequestMapping("myAvatar")
    public String myAvatar(ModelMap model) throws Exception {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        List<Product> productList = new ArrayList<Product>();
        CartInfo cartInfo = null;
        if (acc == null) {
            cartInfo = (CartInfo) redisCacheProvider.get("myCart");
        } else {
            cartInfo = (CartInfo) redisCacheProvider.get("user_" + acc.getId() + "Cart");
        }
        if (cartInfo != null) {
            productList = cartInfo.getProductList();
        } else {
            cartInfo = new CartInfo();
        }
        int productCount = productService.selectProductCount();

        model.addAttribute("cartInfo", cartInfo);
        model.addAttribute("productCount", productCount);
        model.addAttribute("productList", productList);
        Account myData = accountService.selectById(acc.getId());
        if (StringUtils.isEmpty(myData.getHead())) {
            //给一个默认的头像
            myData.setHead("attached/image/head/default.jpg");
        }

        model.addAttribute("imgSrc", myData.getHead());//头像路径
        return "/account/myAvatar";
    }

    private static final int BUFFER_SIZE = 16 * 1024;

    /**
     * 保存头像
     *
     * @param uid
     * @param imageFile
     * @return
     * @throws Exception
     */
    @RequestMapping("saveAvatar")
    public String saveAvatar(HttpServletRequest request,
    		@RequestParam(value = "uid") String uid,
    		@RequestParam(value = "imgFile") MultipartFile imageFile) throws Exception 
    {
        String realPath = request.getSession().getServletContext().getRealPath("/");
        String resourcePath = "account/head/image/";
        if (imageFile != null) {
            Date date = new Date(System.currentTimeMillis());
            String strDate = new SimpleDateFormat("yyyyMMddhhmmss").format(date);
            int random = (int) (Math.random() * 99);
            String imageName = strDate + random;                          //以系统时间来随机的创建图片文件名
            File dir = new File(realPath + resourcePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String saveName = uid + "_" + strDate + random;
            File file = new File(dir, saveName + "_src.jpg");
            imageFile.transferTo(file);

            String expectKey = "attached/image/head/" + saveName + "_src.jpg";//			                String expectKey = "attached/image/head/"+saveName+"_cut.jpg";
            String token = TestConfig.testAuth.uploadToken(TestConfig.bucket, expectKey);
            StringMap params = new StringMap().put("x:foo", "foo_val");
            QiniuUploadManager.uploadFile(file, expectKey, token, params);
            Account account = new Account();
            account.setId(uid);
            account.setHead(expectKey);
            request.setAttribute("e", account);
        }

        return "/account/myAvatarChange";
    }


    public String saveAvatar(ModelMap model, Account account) throws Exception {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }

        File f1, f2;
        f1 = new File(account.getHead());
        int lastLength = account.getHead().lastIndexOf(".");

        Date date = new Date(System.currentTimeMillis());
        String strDate = new SimpleDateFormat("yyyyMMddhhmmss").format(date);
        int random = (int) (Math.random() * 99);
        String imageName = strDate + random;                          //以系统时间来随机的创建图片文件名

        String fileType = account.getHead().substring(lastLength);              //获取上传图片的类型
        String src2 = "/account/head/image/" + imageName + "_src.jpg";
        String src = RequestHolder.getRequest().getRealPath("") + "\\account\\head\\image\\" + imageName + "_src.jpg";

        File f = new File(account.getHead());
        String expectKey = "attached/image/head/" + imageName + "_cut.jpg";//			                String expectKey = "attached/image/head/"+saveName+"_cut.jpg";
//        String expectKey = "attached/image/head/default.jpg";//			                String expectKey = "attached/image/head/"+saveName+"_cut.jpg";
        String token = TestConfig.testAuth.uploadToken(TestConfig.bucket, expectKey);
        StringMap params = new StringMap().put("x:foo", "foo_val");
        QiniuUploadManager.uploadFile(f, expectKey, token, params);
        account.setId(acc.getId());
        account.setHead(expectKey);
        model.addAttribute("e", account);
        return "/account/myAvatarChange";
    }

    private String fileUp(String filePath, String newfileName) throws IOException {
        String resultPath = "";          //上传后图片所在的路径
        FileOutputStream out = null;     //文件输出流
        FileInputStream fr = null;
        try {                               //验证图片上传的格式是否正确
            File f = new File(filePath);

            if (!f.isFile()) {
                throw new Exception(" 不是图片文件!");
            }
            int lastLength = filePath.lastIndexOf(".");
            String fileType = filePath.substring(lastLength);              //获取上传图片的类型
            resultPath = "/jshop/shopindex/layout/image/" + newfileName + fileType;
            File f2 = new File(resultPath);
            if (!f2.exists()) {//判f2是否存在
                f2.mkdirs();// 建立相应的目录
            }
            fr = new FileInputStream(f);
            out = new FileOutputStream(f2);
            byte buffer[] = new byte[1]; // 声明一个byte型的数组，数组的大小是512个字节
            while (fr.read(buffer) != -1) { // read()从此输入流中读取一个数据字节，只要读取的结果不！=-1就执行while循环中的语句块
                out.write(buffer); //write(byte[] b)将 b.length 个字节从指定字节数组写入此文件输出流中。
            }
            f = null;
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            fr.close();
            fr = null;
            out.close();
            out = null;
        }

        return resultPath;
    }


    void copy(File f1, File f2) {//f1 源文件路径  f2目标路径   最后把f2 insert 到数据库就不写了
        try {
            // 建立相关的字节输入流
            FileInputStream fr = new FileInputStream(f1); // 通过打开一个到实际文件的连接来创建一个
            // FileInputStream，该文件通过文件系统中的路径名

            // 创建一个向具有指定名称的文件中写入数据的输出文件流。
            FileOutputStream fw = new FileOutputStream(f2);
            byte buffer[] = new byte[1]; // 声明一个byte型的数组，数组的大小是512个字节
            while (fr.read(buffer) != -1) { // read()从此输入流中读取一个数据字节，只要读取的结果不！=-1就执行while循环中的语句块
                fw.write(buffer); //write(byte[] b)将 b.length 个字节从指定字节数组写入此文件输出流中。
            }
            fw.close();// 关闭此文件输出流并释放与此流有关的所有系统资源。
            fr.close();
            System.out.println("文件" + f1.getName() + "里的内容已拷贝到文件"
                    + f2.getName() + "中！");
        } catch (IOException ioe) {
            System.out.println(ioe);
        } catch (Exception e) {
            System.out.println(e);
        }
    }


    public void bcopy(File f1, File f2) {
        if (f1.exists()) {
            // 判断要拷贝的文件是否存在

            copy(f1, f2);//调用copy方法
            System.out.println("上传文件相关的信息：（名字，路径，大小，最后修改的时间是：）");
            getinfo(f1);
            getinfo(f2);
            System.out.println("上传成功后文件相关的信息：（名字，路径，大小，最后修改的时间是：）");
        } else {
            System.out.println("要拷贝的文件不存在!");
        }
    }

    //获取文件的一些信息
    private void getinfo(File f1) {
        // TODO Auto-generated method stub
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日hh时mm分ss秒");
        if (f1.isFile()) {//isFile()方法是测试此抽象路径名表示的文件是否是一个标准文件。
            System.out.println("文件名称：" + f1.getName());
            System.out.println("文件路径：" + f1.getAbsolutePath());
            System.out.println("文件大小：" + f1.length() + "字节(byte)");
            System.out.println("最后修改的时间是：" + sdf.format(new Date(f1.lastModified())));
        } else {
            System.out.println("上传成功后获取服务器的相关信息：");
            System.out.println("目录名称：" + f1.getName());
            System.out.println("文件路径：" + f1.getAbsolutePath());
            File[] files = f1.listFiles();
            System.out.println("此目录中有" + files.length + "个文件！");
        }
        System.out.println("_______________________________");
    }


    /**
     * 保留	截取图片
     *
     * @param request
     * @param x
     * @param y
     * @param h
     * @param w
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "uploadHeadImage")
    public String uploadHeadImage(
            HttpServletRequest request,
            @RequestParam(value = "x") String x,
            @RequestParam(value = "y") String y,
            @RequestParam(value = "h") String h,
            @RequestParam(value = "w") String w,
            @RequestParam(value = "target") String head
            , ModelMap model)
            throws Exception {
        System.out.println("==========Start=============");
        String realPath = request.getSession().getServletContext().getRealPath("/");
        String resourcePath = "account/head/image/";
        Account acc = LoginUserHolder.getLoginAccount();
        if (head != null) {
            File dir = new File(realPath + resourcePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String saveName = head.substring(head.lastIndexOf("/") + 1, head.lastIndexOf("_"));
            String srcImagePath = realPath + resourcePath + saveName;
            int imageX = 20;
            int imageY = 20;
            int imageH = 120;
            int imageW = 120;
            if (!StringUtils.isEmpty(x))
                imageX = (int) Double.parseDouble(x.replace(" ", ""));
            if (!StringUtils.isEmpty(y))
                imageY = (int) Double.parseDouble(y.replace(" ", ""));
            if (!StringUtils.isEmpty(h))
                imageH = (int) Double.parseDouble(h.replace(" ", ""));
            if (!StringUtils.isEmpty(w))
                imageW = (int) Double.parseDouble(w.replace(" ", ""));

            //这里开始截取操作---------删你妹啊。删我代码。
            System.out.println("==========imageCutStart=============");
            imgCut(srcImagePath, imageX, imageY, imageW, imageH);
            System.out.println("==========imageCutEnd=============");

            //裁剪完毕后上传至七牛
            File f = new File(srcImagePath + "_cut.jpg");
            String expectKey = "attached/image/head/" + saveName + "_cut.jpg";//			                String expectKey = "attached/image/head/"+saveName+"_cut.jpg";
//			                String expectKey = "attached/image/head/default.jpg";//			                String expectKey = "attached/image/head/"+saveName+"_cut.jpg";
            String token = TestConfig.testAuth.uploadToken(TestConfig.bucket, expectKey);
            StringMap params = new StringMap().put("x:foo", "foo_val");
            QiniuUploadManager.uploadFile(f, expectKey, token, params);
            System.out.println("上传七牛成功，删除项目中保存的头像文件");
//			                file.delete();
            f.delete();
            System.out.println("==========updateAccountHeadStart=============");
            Account account = new Account();
            account.setId(acc.getId());
            account.setHead(expectKey);
            accountService.update(account);
            System.out.println("==========updateAccountHeadEnd=============");
        }
//			        }
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        List<Product> productList = new ArrayList<Product>();
        CartInfo cartInfo = null;
        if (acc == null) {
            cartInfo = (CartInfo) redisCacheProvider.get("myCart");
        } else {
            cartInfo = (CartInfo) redisCacheProvider.get("user_" + acc.getId() + "Cart");
        }
        if (cartInfo != null) {
            productList = cartInfo.getProductList();
        } else {
            cartInfo = new CartInfo();
        }
        int productCount = productService.selectProductCount();

        model.addAttribute("cartInfo", cartInfo);
        model.addAttribute("productCount", productCount);
        model.addAttribute("productList", productList);
        return "/account/changeAvatarSuccess";

    }

    /**
     * 截取图片
     *
     * @param srcImageFile 原图片地址
     * @param x            截取时的x坐标
     * @param y            截取时的y坐标
     * @param desWidth     截取的宽度
     * @param desHeight    截取的高度
     */
    public static void imgCut(String srcImageFile, int x, int y, int desWidth,
                              int desHeight) {
        try {
            Image img;
            ImageFilter cropFilter;
            File f = new File(srcImageFile + "_src.jpg");
            BufferedImage bi = ImageIO.read(f);
            int srcWidth = bi.getWidth();
            int srcHeight = bi.getHeight();
            if (srcWidth >= desWidth && srcHeight >= desHeight) {
                Image image = bi.getScaledInstance(srcWidth, srcHeight, Image.SCALE_DEFAULT);
                cropFilter = new CropImageFilter(x, y, desWidth, desHeight);
                img = Toolkit.getDefaultToolkit().createImage(
                        new FilteredImageSource(image.getSource(), cropFilter));
                BufferedImage tag = new BufferedImage(desWidth, desHeight,
                        BufferedImage.TYPE_INT_RGB);
                Graphics g = tag.getGraphics();
                g.drawImage(img, 0, 0, null);
                g.dispose();
                //输出文件
                ImageIO.write(tag, "JPEG", new File(srcImageFile + "_cut.jpg"));
                f.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 地址管理
     *
     * @return
     * @throws Exception
     * @author yantao by 20151202
     */
    @RequestMapping("my_site")
    public String my_site(ModelMap model) throws Exception {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        int productCount = productService.selectProductCount();
        model.addAttribute("productCount", productCount);
        /**
         * 省-市-区
         */
        Map<String, Area> areaMap = loadArea();
        List<Area> cities = new ArrayList<Area>();
        List<Area> areas = new ArrayList<Area>();
        model.addAttribute("provinces", areaMap.values()); //身份
        model.addAttribute("cities", cities);//城市
        model.addAttribute("areas", areas);//区县
        /**
         * 查询个人所有收获地址
         */
        Address address = new Address();
        address.setAccountId(acc.getId());
        List<Address> addressList = addressService.selectList(address);
        if (addressList == null) {
            addressList = new ArrayList<Address>();
        }
        model.addAttribute("addressList", addressList);//收获地址
        model.addAttribute("saveCnt", addressList.size());//已保存条数
        model.addAttribute("cnt", 20 - addressList.size());//还能保存条数
        return "/account/my_site";
    }


    /**
     * 地址修改界面
     *
     * @return
     * @throws Exception
     * @author yantao by 20151202
     */
    @RequestMapping("my_site_up")
    public String my_site_up(ModelMap model) throws Exception {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        List<Product> productList = new ArrayList<Product>();
        CartInfo cartInfo = null;
        if (acc == null) {
            cartInfo = (CartInfo) redisCacheProvider.get("myCart");
        } else {
            cartInfo = (CartInfo) redisCacheProvider.get("user_" + acc.getId() + "Cart");
        }
        if (cartInfo != null) {
            productList = cartInfo.getProductList();
        } else {
            cartInfo = new CartInfo();
        }
        int productCount = productService.selectProductCount();

        model.addAttribute("cartInfo", cartInfo);
        model.addAttribute("productCount", productCount);
        model.addAttribute("productList", productList);
        /**
         * 查询个人所有收获地址
         */
        Address address = new Address();
        address.setAccountId(acc.getId());
        List<Address> addressList = addressService.selectList(address);
        if (addressList == null) {
            addressList = new ArrayList<Address>();
        }
        model.addAttribute("addressList", addressList);//收获地址
        model.addAttribute("saveCnt", addressList.size());//已保存条数
        model.addAttribute("cnt", 20 - addressList.size());//还能保存条数

        String id = RequestHolder.getRequest().getParameter("id");
        address.setId(id);
        Address addressup = addressService.selectOne(address);
        model.addAttribute("address", addressup);

        /**
         * 省-市-区
         */
        Map<String, Area> areaMap = loadArea();
        List<Area> cities = new ArrayList<Area>();
        List<Area> areas = new ArrayList<Area>();
        if (null != addressup.getProvince() && null != areaMap.get(addressup.getProvince()) && StringUtils.isNotBlank(addressup.getProvince())) {
            cities = areaMap.get(addressup.getProvince()).getChildren();
        }
        String area = addressup.getCity();
        for (Area a : cities) {
            if (a.getCode().equals(area)) {
                areas = a.getChildren();
                break;
            }
        }
        model.addAttribute("provinces", areaMap.values()); //身份
        model.addAttribute("cities", cities);//城市
        model.addAttribute("areas", areas);//区县

        return "/account/my_site_up";
    }


    /**
     * 保存配送地址
     * @return
     * @throws Exception
     */
    @RequestMapping("saveMysite")
    public String saveMysite(ModelMap model, Address address) throws Exception 
    {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        int productCount = productService.selectProductCount();
        model.addAttribute("productCount", productCount);
        address.setProvinceId(address.getProvince());

        //需要将省市区的代号换成中文，插入到pcadetail字段里面去，显示的时候方便。
        StringBuilder pcadetail = new StringBuilder();
        Map<String, Area> areaMap = loadArea();
        Area sheng = areaMap.get(address.getProvince());//省
        pcadetail.append(sheng.getName());

        for (int i = 0; i < sheng.getChildren().size(); i++) {
            Area shi = sheng.getChildren().get(i);//市
            if (shi.getCode().equals(address.getCity())) {

                pcadetail.append(" ").append(shi.getName());

                for (int j = 0; j < shi.getChildren().size(); j++) {
                    Area qu = shi.getChildren().get(j);//区
                    if (qu.getCode().equals(address.getArea())) {
                        pcadetail.append(" ").append(qu.getName());
                        break;
                    }
                }
                break;
            }
        }

        address.setPcadetail(pcadetail.toString());
        address.setAccountId(acc.getId());
        if (address.getIsdefault() == null || !address.getIsdefault().equals("y"))
            address.setIsdefault("n");
        if (address.getIsdefault() != null && address.getIsdefault().equals("y")) {
            address.setIsdefault("y");
            //修改其他地址不为默认;
            Address updefault = new Address();
            updefault.setAccountId(acc.getId());
            addressService.upDefault(updefault);
        }

        if (StringUtils.isBlank(address.getId())) {
            addressService.insert(address);
            return "/account/saveAddressSuccess";

        } else {
            addressService.update(address);
            return "/account/changeAddressSuccess";
        }
    }

    /**
     * check配送地址数量
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("checkMysite")
    @ResponseBody
    public Object checkMysite(ModelMap model) 
    {
        Map<String, String> result = new HashMap<String, String>();
        Account acc = LoginUserHolder.getLoginAccount();
        Address address = new Address();
        address.setAccountId(acc.getId());
        int count = addressService.selectCountByAccountId(address);
        if (count > addressCount) {
            result.put("result", "error");
        } else {
            result.put("result", "ok");
        }
        return result;
    }


    @RequestMapping("saveAddressSuccess")
    public String saveAddressSuccess(ModelMap model, Address address) throws Exception {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        List<Product> productList = new ArrayList<Product>();
        CartInfo cartInfo = null;
        if (acc == null) {
            cartInfo = (CartInfo) redisCacheProvider.get("myCart");
        } else {
            cartInfo = (CartInfo) redisCacheProvider.get("user_" + acc.getId() + "Cart");
        }
        if (cartInfo != null) {
            productList = cartInfo.getProductList();
        } else {
            cartInfo = new CartInfo();
        }
        int productCount = productService.selectProductCount();

        model.addAttribute("cartInfo", cartInfo);
        model.addAttribute("productCount", productCount);
        model.addAttribute("productList", productList);
        return "/account/saveAddressSuccess";
    }

    @RequestMapping("changeAddressSuccess")
    public String changeAddressSuccess(ModelMap model, Address address) throws Exception {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        List<Product> productList = new ArrayList<Product>();
        CartInfo cartInfo = null;
        if (acc == null) {
            cartInfo = (CartInfo) redisCacheProvider.get("myCart");
        } else {
            cartInfo = (CartInfo) redisCacheProvider.get("user_" + acc.getId() + "Cart");
        }
        if (cartInfo != null) {
            productList = cartInfo.getProductList();
        } else {
            cartInfo = new CartInfo();
        }
        int productCount = productService.selectProductCount();

        model.addAttribute("cartInfo", cartInfo);
        model.addAttribute("productCount", productCount);
        model.addAttribute("productList", productList);
        return "/account/changeAddressSuccess";
    }


    /**
     * 修改默认地址
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("udpateDefault")
    public String udpateDefault(ModelMap model, Address address) throws Exception {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        //修改其他地址不为默认;
        Address updefault = new Address();
        updefault.setAccountId(acc.getId());
        addressService.upDefault(updefault);

        Address upAddress = new Address();
        upAddress.setAccountId(acc.getId());
        upAddress.setId(address.getId());
        upAddress.setIsdefault("y");
        addressService.setAddressDefault(upAddress);

        return my_site(model);
    }


    /**
     * 删除地址
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("delAddress")
    public String delAddress(ModelMap model, Address address) throws Exception {
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        Address upAddress = new Address();
        upAddress.setId(address.getId());
        addressService.delete(upAddress);

        List<Product> productList = new ArrayList<Product>();
        CartInfo cartInfo = null;
        if (acc == null) {
            cartInfo = (CartInfo) redisCacheProvider.get("myCart");
        } else {
            cartInfo = (CartInfo) redisCacheProvider.get("user_" + acc.getId() + "Cart");
        }
        if (cartInfo != null) {
            productList = cartInfo.getProductList();
        } else {
            cartInfo = new CartInfo();
        }
        int productCount = productService.selectProductCount();

        model.addAttribute("cartInfo", cartInfo);
        model.addAttribute("productCount", productCount);
        model.addAttribute("productList", productList);
        /**
         * 省-市-区
         */
        Map<String, Area> areaMap = loadArea();
        List<Area> cities = new ArrayList<Area>();
        List<Area> areas = new ArrayList<Area>();
        model.addAttribute("provinces", areaMap.values()); //身份
        model.addAttribute("cities", cities);//城市
        model.addAttribute("areas", areas);//区县
        /**
         * 查询个人所有收获地址
         */
        Address add = new Address();
        add.setAccountId(acc.getId());
        List<Address> addressList = addressService.selectList(add);
        if (addressList == null) {
            addressList = new ArrayList<Address>();
        }
        model.addAttribute("addressList", addressList);//收获地址
        model.addAttribute("saveCnt", addressList.size());//已保存条数
        model.addAttribute("cnt", 20 - addressList.size());//还能保存条数
        return "/account/my_site";
    }

    /**
     * 申请售后/客户服务跳转
     * jiangyongzhi
     * @return
     */
    @RequestMapping("custService")
    public String orderRepairs(ModelMap model) throws Exception 
    {
        logger.info("申请售后orderRepairs...");
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) 
        {
            return toLogin;
        }
        int productCount = productService.selectProductCount();
        model.addAttribute("productCount", productCount);
        String id = RequestHolder.getRequest().getParameter("id");
        String productID = RequestHolder.getRequest().getParameter("productID");

        if (!StringUtils.isBlank(id) && !StringUtils.isBlank(productID)) {
            List<Order> orderList = new ArrayList<Order>();
            logger.info("商品售后申请：订单号" + id + ",商品编号" + productID);
            Order order = new Order();
            order.clear();
            order.setAccount(acc.getId());
            order.setId(id);
            // 2、查询指定订单集合的所有订单项集合，然后内存中对订单项进行分组
            List<Order> myOrders = orderService.selectOrderInfo(order);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (Order order2 : myOrders) {
                //商品规格
                if (!StringUtils.isBlank(order2.getSpecInfo()) && order2.getSpecInfo().indexOf(",") > 0) {
                    order2.setSpecInfo(order2.getSpecInfo().replace(",", "<br />"));
                    logger.debug("-------SpecInfo----------" + order2.getSpecInfo());
                }
                if (String.valueOf(order2.getProductID()).equals(productID)) {
                    orderList.add(order2);
                    for (Iterator<Order> it = orderList.iterator(); it
                            .hasNext(); ) {
                        Order orderdetail = it.next();
                        orderdetail.setCreatedate(DateTimeUtil
                                .getDateTimeString(sdf.parse(order2
                                        .getCreatedate())));
                        orderdetail.setPayTime(order2.getPayTime());
                        orderdetail.getOrders().add(order2);
                    }
                }
            }

            model.addAttribute("orderList", orderList);
            return "account/custService";
        } else {
            logger.info("所有售后商品");

            int offset = 0;
            if (RequestHolder.getRequest().getParameter("pager.offset") != null) {
                offset = Integer
                        .parseInt(RequestHolder.getRequest().getParameter("pager.offset"));
            }
            if (offset < 0)
                offset = 0;

            PagerModel pager = new PagerModel();
            OrderRepairs op = new OrderRepairs();
            op.setUserId(acc.getId());
            if (!StringUtils.isBlank(RequestHolder.getRequest().getParameter("status"))) {
                op.setRepairType(Integer.valueOf(RequestHolder.getRequest().getParameter("status")));
            }
            pager = orderRepairsService.selectFrontPageList(op);
            List<MyOrderRepairs> myorders = (List<MyOrderRepairs>) pager.getList();
            List<OrderRepairs> OrderRepairsList = orderRepairsService.selectByUserId(op);
            List<MyOrderRepairs> myOrderRepairsList = new ArrayList<MyOrderRepairs>();

            for (OrderRepairs orderRepairs : OrderRepairsList) {
                for (MyOrderRepairs myOrderRepairs : myorders) {

                    if (orderRepairs.getOrderId().equals(myOrderRepairs.getId())) {
                        myOrderRepairsList.add(myOrderRepairs);
                        break;
                    }
                }
            }

            for (MyOrderRepairs myOrderRepairsInfo : myOrderRepairsList) {

                for (MyOrderRepairs myOrderRepairs : myorders) {

                    //商品规格
                    if (!StringUtils.isBlank(myOrderRepairs.getSpecInfo()) && myOrderRepairs.getSpecInfo().indexOf(",") > 0) {
                        myOrderRepairs.setSpecInfo(myOrderRepairs.getSpecInfo().replace(",", "<br />"));
                        logger.debug("-------SpecInfo----------" + myOrderRepairs.getSpecInfo());
                    }

                    if (myOrderRepairsInfo.getId().equals(myOrderRepairs.getId())) {
                        myOrderRepairsInfo.getOrders().add(myOrderRepairs);
                    }
                }
            }
            model.addAttribute("pager", myOrderRepairsList);
            model.addAttribute("repairsSimpleReport", orderRepairsService.selectRepairSimpleReport(op));
        }
        return "account/custServices";
    }
    
    
    
    /**
     * 申请售后/客户服务跳转
     * @return
     */
    @RequestMapping("saveCustService")
    public String saveCustService(HttpServletRequest request,
    		@RequestParam(value = "repairImg") MultipartFile imageFile) throws Exception 
    {
    	OrderRepairs op = new OrderRepairs();
    	op.setUserInfo(request.getParameter("userInfo"));
    	op.setAddAcount(request.getParameter("addAcount"));
    	op.setAddTel(request.getParameter("addAcount"));
    	op.setAddAdr(request.getParameter("addAdr"));
    	op.setTencentQQ(request.getParameter("tencentQQ"));
    	op.setRepairImg(request.getParameter("repairImg"));
    	op.setOrderId(request.getParameter("orderId"));
    	op.setRepairDescription(request.getParameter("repairDescription"));
    	op.setRepairType(Integer.valueOf(request.getParameter("repairType")));
    	 logger.info("申请售后提交orderRepairs...");
         Account acc = LoginUserHolder.getLoginAccount();
         if (acc == null || StringUtils.isBlank(acc.getAccount())) 
         {
             return toLogin;
         }
         op.setUserId(acc.getId());
         op.setStatus(OrderRepairs.order_status_sale);//1处理中
         if (StringUtils.isBlank(op.getUserInfo())) {
             op.setUserInfo("");
         }
         if (!StringUtils.isBlank(op.getAddAcount())) {
             op.setUserInfo("申请人：" + op.getUserInfo() + op.getAddAcount() + " ");
         }
         if (!StringUtils.isBlank(op.getAddTel())) {
             op.setUserInfo("手机号：" + op.getUserInfo() + op.getAddTel() + " ");
         }
         if (!StringUtils.isBlank(op.getAddAdr())) {
             op.setUserInfo("地址：" + op.getUserInfo() + op.getAddAdr() + " ");
         }
         if (!StringUtils.isBlank(op.getTencentQQ())) {
             op.setUserInfo("联系qq：" + op.getUserInfo() + op.getTencentQQ() + " ");
         }
         
         Properties  properties = PropertiesUtil.findCommonPro("config.properties");
         String realPath = request.getSession().getServletContext().getRealPath("/");
         String imagetemp = properties.getProperty("imagetemp");
         if (imageFile != null) {
         	File dir = new File(realPath + imagetemp);
             if (!dir.exists()) {
                 dir.mkdirs();
             }
             Date date = new Date(System.currentTimeMillis());
             String strDate = new SimpleDateFormat("yyyyMMddhhmmss").format(date);
             int random = (int) (Math.random() * 99);
             String imageName = strDate + random; 
             op.setRepairImg(imageFile.getOriginalFilename());
             int lastLength = op.getRepairImg().lastIndexOf(".");
             String fileType = op.getRepairImg().substring(lastLength);              //获取上传图片的类型
             String src2 = realPath+imagetemp + imageName + fileType;
             op.setRepairImg(src2);
             File f1 = new File(op.getRepairImg());
             imageFile.transferTo(f1);
             String token = TestConfig.testAuth.uploadToken(TestConfig.bucket, imagetemp + imageName + fileType);
             StringMap params = new StringMap().put("x:foo", "foo_val");
             QiniuUploadManager.uploadFile(f1, imagetemp + imageName + fileType, token, params);
             op.setRepairImg(imagetemp + imageName + fileType);
         }
         orderRepairsService.insertFront(op);
         //修改t_order是否售后订单状态字段
         orderService.updateOrderIsSaleorderById(op.getOrderId());
         return "redirect:custService";
    }


    /**
     * 申请售后/确认完成  （买家不需要确认，该方法不用）
     * @return
     */
    @RequestMapping("alert_sure")
    public String alertSure(ModelMap model) throws Exception {
        logger.info("申请售后确认完成alertSure...");
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        String id = RequestHolder.getRequest().getParameter("id");
        if (StringUtils.isBlank(id)) {
            throw new NullPointerException("非法请求！");
        }
        OrderRepairs op = new OrderRepairs();
        op.setId(id);
        op.setUserId(acc.getId());
        op.setStatus(OrderRepairs.order_status_process);//3已处理

        orderRepairsService.update(op);
        return "redirect:custService";
    }

    /**
     * 售后详情
     * jiangyongzhi
     * @return
     */
    @RequestMapping("custServiceDetail")
    public String custServiceDetail(ModelMap model) throws Exception 
    {
        logger.info("售后详情custServiceDetail...");
        Account acc = LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) 
        {
            return toLogin;
        }
        CartInfo cartInfo = null;
        List<Product> productList = new ArrayList<Product>();
        if (acc == null) 
        {
            cartInfo = (CartInfo) redisCacheProvider.get("myCart");
        } 
        else 
        {
            cartInfo = (CartInfo) redisCacheProvider.get("user_" + acc.getId() + "Cart");
        }
        if (cartInfo != null) 
        {
            productList = cartInfo.getProductList();
        } 
        else 
        {
            cartInfo = new CartInfo();
        }
        int productCount = productService.selectProductCount();
        model.addAttribute("cartInfo", cartInfo);
        model.addAttribute("productCount", productCount);
        model.addAttribute("productList", productList);
        String id = RequestHolder.getRequest().getParameter("id");

        if (!StringUtils.isBlank(id)) 
        {
            List<MyOrderRepairs> orderList = new ArrayList<MyOrderRepairs>();
            logger.info("商品售后详情：订单号" + id);
            OrderRepairs order = new OrderRepairs();
            order.clear();
            order.setUserId(acc.getId());
            order.setId(id);
            // 2、查询指定订单集合的所有订单项集合，然后内存中对订单项进行分组
            List<MyOrderRepairs> myOrders = orderRepairsService.selectOrderInfoList(order);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            MyOrderRepairs orderInfo = new MyOrderRepairs();
            if (myOrders != null && myOrders.size() != 0) 
            {
                orderInfo = myOrders.get(0);
                for (MyOrderRepairs order2 : myOrders) 
                {
                    //商品规格
                    if (!StringUtils.isBlank(order2.getSpecInfo()) && order2.getSpecInfo().indexOf(",") > 0) 
                    {
                        order2.setSpecInfo(order2.getSpecInfo().replace(",", "<br />"));
                        logger.debug("-------SpecInfo----------" + order2.getSpecInfo());
                    }
                    orderList.add(order2);
                    for (Iterator<MyOrderRepairs> it = orderList.iterator(); it.hasNext(); ) 
                    {
                        MyOrderRepairs orderdetail = it.next();
                        orderdetail.setCreatedate(DateTimeUtil
                                .getDateTimeString(sdf.parse(order2.getCreatedate())));
                        orderdetail.setPayTime(order2.getPayTime());
                        orderdetail.getOrders().add(order2);
                    }
                }
            }
            model.addAttribute("orderInfo", orderInfo);
            model.addAttribute("orderList", orderList);
            OrderRepairs e = orderRepairsService.selectById(id);
            model.addAttribute("e", e);
        }
        return "account/custServiceDetail";
    }


    /**
     * 分页查询消费记录
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("expenseRecord")
    public String expenseRecordsPage(ModelMap model) throws Exception {
        Account acc = (Account) LoginUserHolder.getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
            return toLogin;
        }
        List<Product> productList = new ArrayList<Product>();
        CartInfo cartInfo = null;
        if (acc == null) {
            cartInfo = (CartInfo) redisCacheProvider.get("myCart");
        } else {
            cartInfo = (CartInfo) redisCacheProvider.get("user_" + acc.getId() + "Cart");
        }
        if (cartInfo != null) {
            productList = cartInfo.getProductList();
        } else {
            cartInfo = new CartInfo();
        }
        int productCount = productService.selectProductCount();

        model.addAttribute("cartInfo", cartInfo);
        model.addAttribute("productCount", productCount);
        model.addAttribute("productList", productList);
        Order order = new Order();
        order.setAccount(acc.getAccount());
        PagerModel pager = selectPagerExpenseRecordList(order);


        // selectLeftMenu = FrontContainer.user_leftMenu_favorite;
        model.addAttribute("pager", pager);
        return "/account/expenseRecord";
    }


    private PagerModel selectPagerExpenseRecordList(Order order) {
        int offset = 0;
        String pagerOffset = RequestHolder.getRequest().getParameter("pager.offset");
        if (StringUtils.isNotBlank(pagerOffset)) {
//			throw new NullPointerException();
            offset = (int) Double.parseDouble(pagerOffset);
        }
        if (offset < 0)
            offset = 0;
        order.setOffset(offset);
        PagerModel servicesPager = orderService.selectExpenseRecordsList(order);
        if (servicesPager == null) servicesPager = new PagerModel();
        // 计算总页数
        servicesPager.setPagerSize((servicesPager.getTotal() + servicesPager.getPageSize() - 1)
                / servicesPager.getPageSize());
        return servicesPager;
    }

    /**
     * 拦截404错误跳转页面
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "to404", method = RequestMethod.GET)
    public String to404(ModelMap model) throws Exception {
        CartInfo cartInfo = getMyCart();
        List<Product> productList = new ArrayList<Product>();
        if (cartInfo != null) {
            productList = cartInfo.getProductList();
        } else {
            cartInfo = new CartInfo();
        }
        model.addAttribute("cartInfo", cartInfo);
        model.addAttribute("productList", productList);
        logger.info("跳转404页面！");
        return "404Ftl";
    }

    protected CartInfo getMyCart() {
        //return (CartInfo) RequestHolder.getSession().getAttribute(FrontContainer.myCart);
        Account account = LoginUserHolder.getLoginAccount();    //得到登录用户的信息
        CartInfo cartInfo = null;
        if (account == null) {
            cartInfo = (CartInfo) redisCacheProvider.get("myCart");
        } else {
            cartInfo = (CartInfo) redisCacheProvider.get("user_" + account.getId() + "Cart");
        }
        return cartInfo;
    }

    /**
     * 加载省市区数据
     */
    public Map<String, Area> loadArea() {
        logger.error("loadArea...");
        Area area = new Area();
        List<Area> areas = areaService.selectFrontList(area);
        List<Area> rootAreas = Lists.newArrayList();
        for (Area a : areas) {
            if ("100000".equals(a.getPcode())) {
                rootAreas.add(a);
            }
        }
        if (rootAreas.size() == 0) {
            return null;
        }

        for (Area a : rootAreas) {
            this.getAreaByDigui2(a, areas);
        }

        Map<String, Area> map = new TreeMap<String, Area>();
        for (Area a : rootAreas) {
            map.put(a.getCode(), a);
        }
        return map;
    }

    /**
     * 递归加载省份下的：城市、区域、以后还会有街道的数据
     *
     * @param item
     */
    private void getAreaByDigui2(Area item) {
        Area area = new Area();
        area.setPcode(item.getCode());
        List<Area> children = areaService.selectFrontList(area);
        if (children == null) {
            return;
        }
        item.setChildren(children);
        for (int i = 0; i < children.size(); i++) {
            getAreaByDigui2(children.get(i));
        }
    }

    /**
     * 递归加载省份下的：城市、区域、以后还会有街道的数据
     *
     * @param item
     * @param areas 所有的地区列表
     */
    private void getAreaByDigui2(Area item, final List<Area> areas) {
        List<Area> children = Lists.newArrayList();
        for (Area a : areas) {
            if (item.getCode().equals(a.getPcode())) {
                children.add(a);
            }
        }

        item.setChildren(children);
        if (children.size() == 0) {
            return;
        }

        for (Area a : children) {
            getAreaByDigui2(a, areas);
        }
    }
}

